package com.ibangnuo.manage.service.employee;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ibangnuo.framework.domain.CommercialTenant;
import com.ibangnuo.framework.domain.Role;
import com.ibangnuo.framework.domain.User;
import com.ibangnuo.framework.domain.UserRole;
import com.ibangnuo.framework.domain.request.employee.AssistantRequest;
import com.ibangnuo.framework.model.response.CommonCode;
import com.ibangnuo.framework.model.response.QueryResponseResult;
import com.ibangnuo.framework.model.response.QueryResult;
import com.ibangnuo.framework.utils.MD5Utils;
import com.ibangnuo.framework.utils.PrimaryKeyUtil;
import com.ibangnuo.manage.dao.RoleRepository;
import com.ibangnuo.manage.dao.UserMapper;
import com.ibangnuo.manage.dao.UserRepository;
import com.ibangnuo.manage.dao.UserRoleRepository;
import com.ibangnuo.manage.dao.employee.CommercialMapper;
import com.ibangnuo.manage.dao.employee.CommercialRepository;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.constraints.Null;
import java.util.*;

/**
 * @Author:ly
 * @Data:2019/12/30 10:48
 * @Verdion:1.0
 */
@Service
public class AssistantService {

    private static Logger LOGGER = LoggerFactory.getLogger(AssistantService.class);
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CommercialMapper commercialMapper;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private RoleRepository roleRepository;

    /**
     * 添加店员
     * 1.先获取该登录者的userID
     * 2.获取商户id
     * 3.判断表单中的用户名是否在数据库中存在
     * 3.根据商户id添加店员user
     *
     * @param assistantRequest
     * @return
     */
    public QueryResponseResult addAssistant(AssistantRequest assistantRequest) {
        LOGGER.info("添加店员的参数:{}", assistantRequest.toString());
        if (assistantRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        String username = assistantRequest.getAssistantUsername();
        User byUsername = userRepository.findByUsername(username);
        System.out.println(byUsername);
        if (byUsername != null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String user1Id = user1.getId();
        CommercialTenant commercialTenant = commercialMapper.findByUserId(user1Id);
        User user = new User();
        String password = MD5Utils.md5(assistantRequest.getAssistantPassword(), "wang");
        user.setPassword(password);
        user.setUsername(assistantRequest.getAssistantUsername());
        user.setPhone(assistantRequest.getAssistantPhone());
        user.setName(assistantRequest.getAssistantName());
        user.setCreateTime(new Date());
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString().replace("-", "");
//        user.setId(id);
        user.setIsDelete(1);
        user.setStatus(1);
        long number = PrimaryKeyUtil.nextId();
        user.setNumber(Long.toString(number));
        user.setEmail(assistantRequest.getAssistantEmail());
        if (assistantRequest.getAssistantSex().equals("男")) {
            user.setSex(0);
        } else {
            user.setSex(1);
        }
        user.setType(5);
        user.setCommercialTenantId(commercialTenant.getId());
        String shopId = assistantRequest.getTerminalAgentId();
        user.setShopId(shopId);
        userRepository.save(user);
//        userMapper.insertUser(user);
        UserRole userRole = new UserRole();
        userRole.setCreateTime(new Date());
        Role assistant = roleRepository.findByRoleCode("assistant");
        userRole.setRoleId(assistant.getId());
        userRole.setUserId(id);
        userRoleRepository.save(userRole);
        return new QueryResponseResult(CommonCode.SUCCESS, null);

    }


    /**
     * 查询店员
     * 1.先获取该登录者的userID
     * 2.获取商户id
     * 3.在根据userid查询所有的user
     *
     * @param assistantRequest
     * @return
     */
    public QueryResponseResult userQuery(AssistantRequest assistantRequest) {
        LOGGER.info("查询店员的参数:{}", assistantRequest.toString());
        if (assistantRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        User user1 = (User) SecurityUtils.getSubject().getPrincipal();
        String user1Id = user1.getId();
        if (user1.getType()==0){
            //管理员查询
        }else{
            //商户查询
            CommercialTenant commercialTenant = commercialMapper.findByUserId(user1Id);
            String commercialTenantId = commercialTenant.getId();
            assistantRequest.setCommercialTenantId(commercialTenantId);
        }

        String page1 = assistantRequest.getPage();
        int page = Integer.parseInt(page1);
        String limit = assistantRequest.getLimit();
        int size = Integer.parseInt(limit);
        if (page <= 0) {
            page = 1;
        }
        if (size <= 0) {
            size = 5;
        }
        PageHelper.startPage(page, size);
        List<Map> list = userMapper.findBycommercialTenantId(assistantRequest);
        PageInfo<Map> pageInfo = new PageInfo(list);
        QueryResult queryResult = new QueryResult();
        List<Map> userList = pageInfo.getList();
        for (Map map : userList) {
            Integer sex = (Integer) map.get("assistantSex");
            if (sex == 1) {
                map.put("assistantSex", "女");
            } else if (sex==0){
                map.put("assistantSex", "男");
            }else{
                map.put("assistantSex",null);
            }
        }
        queryResult.setList(pageInfo.getList());
        queryResult.setTotal(pageInfo.getTotal());
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }

    /**
     * 删除店员
     *
     * @param assistantNumber
     * @return
     */
    public QueryResponseResult delAssistant(String assistantNumber) {
        LOGGER.info("删除店员的参数:{}", assistantNumber);
        if (assistantNumber != null && !"".equals(assistantNumber) && !"null".equals(assistantNumber)) {
            Optional<User> byId = userRepository.findById(assistantNumber);
            User user = byId.get();
            user.setIsDelete(0);
            userRepository.save(user);
            return new QueryResponseResult(CommonCode.SUCCESS, null);
        }
        return new QueryResponseResult(CommonCode.FAIL, null);
    }

    /**
     * 店员信息回显
     *
     * @param assistantNumber
     * @return
     */
    public QueryResponseResult findById(String assistantNumber) {
        LOGGER.info("店员信息回显参数:{}", assistantNumber);
        if (assistantNumber == null || "".equals(assistantNumber) || "null".equals(assistantNumber)) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        List<Map> all = userMapper.findByUserId(assistantNumber);
        for (Map map : all) {
            Object assistantSex1 = map.get("assistantSex");
            System.out.println(assistantSex1);
            int assistantSex = (int) map.get("assistantSex");
            if (assistantSex == 0) {
                map.put("assistantSex", "男");
            } else {
                map.put("assistantSex", "女");
            }

        }
        QueryResult queryResult = new QueryResult();
        if (all.size() > 0 && all != null) {
            queryResult.setList(all);
            queryResult.setTotal(all.size());
        }
        return new QueryResponseResult(CommonCode.SUCCESS, queryResult);
    }


    /**
     * 店员编辑
     *
     * @param assistantRequest
     * @return
     */
    public QueryResponseResult upAssistant(AssistantRequest assistantRequest) {

        LOGGER.info("编辑店员的参数:{}", assistantRequest.toString());
        if (assistantRequest == null) {
            return new QueryResponseResult(CommonCode.FAIL, null);
        }
        Optional<User> byId = userRepository.findById(assistantRequest.getAssistantNumber());
        User user = byId.get();
        if (assistantRequest.getAssistantPassword() == null) {
            user.setPassword(user.getPassword());
        }
        String password = MD5Utils.md5(assistantRequest.getAssistantPassword(), "wang");
        user.setPassword(password);
        user.setPhone(assistantRequest.getAssistantPhone());
        user.setName(assistantRequest.getAssistantName());
        user.setUpdateTime(new Date());
        user.setEmail(assistantRequest.getAssistantEmail());
        if (assistantRequest.getAssistantSex().equals("男")) {
            user.setSex(0);
        } else {
            user.setSex(1);
        }
        User save = userRepository.save(user);
       /* UserRole userRole = new UserRole();
        userRole.setCreateTime(new Date());
        userRole.setRoleId(assistantRequest.getRoleId());
        userRole.setUserId(save.getId());
        userRoleRepository.save(userRole);*/
        return new QueryResponseResult(CommonCode.SUCCESS, null);

    }
}
